//! @Author: DengLibin
//! @Date: Create in 2024-07-17 15:38:01
//! @Description:

use lazy_static::lazy_static;
use log::info;

use std::sync::Arc;

use sqlx::{MySql, Pool};
use tokio::sync::Mutex;

use crate::{
    dao::{self, mysql::user_mysql_dao},
    entity::user::User,
    sys::global::GlobalResult,
};

lazy_static! {
    static ref   USER_MUTEX: Arc<Mutex<()>> = Arc::new(Mutex::<()>::new(())); // 创建一个互斥锁
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-19 16:36:46
/// @Description: 添加
pub async fn insert_user(user: User, pool: &Pool<MySql>) -> GlobalResult<User> {
    let _g = USER_MUTEX.lock().await;
    let s = my_util_lib::date::get_sys_timestamp_millis();
    if let Some(u_name) = &user.user_login_name {
        let c = user_mysql_dao::count_user_login_name(u_name, pool).await?;
        let e = my_util_lib::date::get_sys_timestamp_millis();
        info!("count_user_login_name:{}ms", e - s);
        if c > 0 {
            return Err(anyhow::anyhow!("用户名已存在".to_string()));
        }

        return dao::mysql::mysql_dao::insert_one(user, pool).await;
    } else {
        return Err(anyhow::anyhow!("用户名不能为空".to_string()));
    }
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-22 14:55:54
/// @Description: 根据登录名查询
pub async fn get_by_login_name(
    user_login_name: &str,
    pool: &Pool<MySql>,
) -> GlobalResult<Option<User>> {
    user_mysql_dao::get_user_login_name(user_login_name, pool).await
}
